﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iSun.Model;
using iSun.Entity;
using iSun.Common;
using iSun.BLL;

namespace iSun.BLL
{
    /// <summary>
    /// 用户的业务逻辑
    /// </summary>
    public partial class BUser : BLL.Base.BaseBussnies
    {
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public BUser()
        {
            this.entity = new DatUser();
            this.User.GetDataCheckMessage();
        }

        public BUser(DatUser user)
        {
            this.entity = user;
        }

        /// <summary>
        /// 用户
        /// </summary>
        public DatUser User
        {
            get
            {
                return this.entity as DatUser;
            }
        }

        /// <summary>
        /// 数据验证
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>返回字符串</returns>
        public override string CheckData(BaseEntity entity)
        {
            DatUser dtUser = entity as DatUser;
            if (string.IsNullOrEmpty(dtUser.LoginName))
            {
                return "用户名不能为空!";
            }
            else if (string.IsNullOrEmpty(dtUser.Password))
            {
                return "密码不能为空!";
            }
            return base.CheckData(dtUser);
        }


        /// <summary>
        /// 判断用户名是否已存在
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>true:已存在 false:不存在</returns>
        public bool IsExist(DatUser entity)
        {
            return GetEntityByCondition("LoginName='" + entity.LoginName + "'") != null;
        }


        /// <summary>
        /// 判断用户名是否已存在
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <returns>true:已存在 false:不存在</returns>
        public bool IsExist(string LoginName)
        {
            return GetEntityByCondition("LoginName='" + LoginName + "'") != null;
        }


        /// <summary>
        /// 修改用户时判断用户名登录名是否已存在
        /// </summary>
        /// <param name="LoginName">用户名</param>
        /// <returns>true:已存在 false:不存在</returns>
        public bool IsExist(string LoginName, Guid userId)
        {
            return GetEntityByCondition("LoginName='" + LoginName + "' and UserID!='" + userId + "'") != null;
        }
        /// <summary>
        /// 判断用户名和密码是否正确
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>true:成功 false:失败</returns>
        public DatUser GetDatUserByLoginNameAndPwd(DatUser entity)
        {
            return GetEntityByCondition("LoginName ='" + entity.LoginName + "' and Password='" + entity.Password + "'") as DatUser;
        }


        /// <summary>
        /// 根据名称判断用户是否存在
        /// </summary>
        /// <param name="uName"></param>
        /// <returns></returns>
        public DatUser GetDatUserByUName(string uName)
        {
            return GetEntityByCondition("LoginName='" + uName + "'") as DatUser;
        }
        /// <summary>
        /// 判断用户名和密码是否正确
        /// </summary>
        /// <param name="Name">登录名</param>
        /// <param name="Password">密码</param>
        /// <returns></returns>
        public DatUser GetDatUserByLoginNameAndPwd(string  Name ,string Password)
        {
            DatUser dtusr = null;
            if (!string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Password)) 
            {
                dtusr = new DatUser();
                dtusr.LoginName = Name;
                dtusr.Password = ExtendMethods.GetMd5Hash(Password);
                dtusr= GetDatUserByLoginNameAndPwd(dtusr);
            }
            return dtusr;
        }

        /// <summary>
        /// 根据用户ID获取系统功能权限集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回系统功能权限集合</returns>
        public IList<SysFunction> GetFunctionByUserId(Guid userId)
        {
            return this.GetEntitysBySqlComm<SysFunction>("Select * from V_SysFunction where  UserID='" + userId + "' and (IsMenu<>'N' or IsMenu is Null)");
        }


        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string GetDataCondition(Guid? FunctionID,string Entity)
        {
            return GetDataCondition(this.User.UserID,FunctionID,Entity);
        }

        /// <summary>
        /// 获取数据权限
        /// </summary>
        /// <param name="UserID">当前用户</param>
        /// <param name="FunctionID">当前功能</param>
        /// <param name="Entity">当前实体</param>
        /// <returns></returns>
        public string GetDataCondition(Guid? UserID,Guid? FunctionID, string Entity)
        {
            IList<Entity.SysRoleFunction> list = GetRoleFunction(UserID,FunctionID);
            StringBuilder strCondition = new StringBuilder("");

            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        if (Entity == "V_HF_TaskInstanceView")
                        {
                            strCondition.Append(string.Format(" opercontent='ALL' or opercontent='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (Entity == "V_HF_ClaimedWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (Entity == "V_HF_CompleteWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (Entity == "V_HF_MyAllWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        else if (Entity == "V_HF_AbnormalTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                        }
                        /* else if (Entity == "V_CrmCustomerInfo")
                         {
                             string strTreeId = this.GetStringFromQueryString("condition", "");
                             if (strTreeId == "")
                             {
                                 strCondition.Append(string.Format(" CustomUser='{0}'", this.UserId));
                             }
                             else
                             {
                                 strCondition.Append(string.Format(" {0}", strTreeId));
                             }
                         }
                         else if (Entity == "V_CrmCustomer")
                         {
                             strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate=0", this.UserId));
                         }*/
                        else
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(string.Format(" AddUser='{0}'", UserID));
                        }
                        break;
                    ///可以看本部门的
                    case "1":
                        if (Entity == "V_CrmCustomerShow")
                        {
                            strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate=0 and IsValue=1", UserID));

                        }
                        else
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(string.Format(" AddUser in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", UserID));
                        }
                        break;
                    // 全部数据
                    case "2":
                        break;
                    //自定义部门条件
                    case "3":
                        // 如果自定义条件
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append(string.Format(" AddUser in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", entity.Depts));
                        break;
                    // 自定义条件数据
                    case "4":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        if (entity.Condition != string.Empty)
                        {
                            strCondition.Append(" " + entity.Condition + " ");
                        }
                        break;
                    default:
                        break;
                }
            }

            //只用客户用户时使用
            if (this.User.IsOutsite == true)
            {
                if (Entity == "TrActivity")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID='{0}')", User.CustomerID));

                }
                if (Entity == "V_TrActivityCourse")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }
                    strCondition.Append(string.Format("(TrCustomerID = '{0}')", User.CustomerID));
                }
            }
            return string.IsNullOrEmpty(strCondition.ToString()) ? "" : "(" + strCondition.ToString() + ")"; 
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>-1,成功，0，用户不存在，1，用户过期，2，密码不对</returns>
        public int Login(string username, string password,out DatUser user)
        {
            user = GetEntityByCondition<DatUser>("LoginName='" + username + "'");

            if(user == null)
            {
                return 0;
            }
            //过期
            //if (user.ExpireDate < System.DateTime.Now)
            //{
            //    return 1;
            //}
            //过期
            if (user.IsExpire)
            {
                return 1;
            }

            //密码不符合
            if (user.Password != password.GetMd5Hash())
            {
                //if (user.Password != iSun.Common.File.DesEncrypt.Decrypt(password, "123").GetMd5Hash())
                {
                    return 2;
                }
                //return 2;
            }
            else
            {
                return -1;
            }
        }


        /// <summary>
        /// 根据用户ID获取系统功能权限集合
        /// </summary>                                     
        /// <param name="userId">用户ID</param>
        /// <returns>返回系统功能权限集合</returns>
        public bool ExistFunction(Guid userId,Guid functionId)
        {
            var list = this.GetEntitysBySqlComm<SysFunction>("Select * from V_SysFunction where  UserID='" + userId + "' and functionId='"+functionId+"'");
            if (list == null)
            { return false; }
            if (list.Count == 0)
            { return false; }
            return true;
            //return GetEntitysByCondition("UserID='" + userId + "'") as IList<VSysfunction>;
        }



        /// <summary>
        ///  
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="functionID"></param>
        /// <returns></returns>
        public IList<SysRoleFunction> GetRoleFunction(Guid? userID,Guid? functionID)
        {
            string strSql = @"SELECT   dbo.SysRoleFunction.*
                      FROM dbo.SysRoleFunction INNER JOIN
                      dbo.SysRole ON dbo.SysRoleFunction.RoleID = dbo.SysRole.RoleID INNER JOIN
                      dbo.SysUserRole ON dbo.SysRole.RoleID = dbo.SysUserRole.RoleID INNER JOIN
                      dbo.DatUser ON dbo.SysUserRole.UserID = dbo.DatUser.UserID
                      where dbo.DatUser.userID='{0}' and functionid='{1}'";
            return this.GetEntitysBySqlComm<SysRoleFunction>(string.Format(strSql, userID, functionID));
        }


        /// <summary>
        /// 根据用户ID获取用户角色集合
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回用户角色集合</returns>
        public IList<SysRole> GetUserRoleByUserId(Guid userId)
        {
            return GetEntitysBySqlComm<SysRole>("Select * from V_SysRole where UserID='" + userId + "'");
        }
        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>返回用户实体对象</returns>
        public DatUser GetDatUserByUserId(Guid userId)
        {
            return GetEntityByCondition<DatUser>("UserID='" + userId + "'") as DatUser;
        }
        /// <summary>
        /// 根据用户名获取用户实体对象
        /// </summary>
        /// <param name="name">用户名</param>
        /// <returns>用户实体对象</returns>
        public DatUser GetDatUserByName(string name)
        {
            return GetEntityByCondition<DatUser>("LoginName='" + name + "'") as DatUser;
        }
        /// <summary>
        /// 判断职员和人员是否已被选择
        /// </summary>
        /// <param name="CustomerID">客户ID</param>
        /// <param name="EmpID">职员ID</param>
        /// <param name="UserId">用户ID</param>
        /// <param name="IsOutsite">是否为外部用户</param>
        /// <returns></returns>
        public bool GetDatUserByID(Guid CustomerID, Guid EmpID, Guid UserId, bool IsOutsite)
        {
            bool temp = false;
            if (IsOutsite == true && CustomerID !=Guid.Empty)  //是
            {
                temp = GetEntityByCondition("CustomerID='" + CustomerID + "' and UserID!='" + UserId + "'") != null;
            }
            else if (IsOutsite == false && EmpID != Guid.Empty)  //否
            {
                temp = GetEntityByCondition("EmpID='" + EmpID + "' and UserID!='" + UserId + "'") != null;
            }
            return temp;                                                                                 
        }
        /// <summary>
        /// 根据邮箱获取用户实体对象
        /// </summary>
        /// <param name="email">邮箱</param>
        /// <returns>用户实体对象</returns>
        public DatUser GetDatUserByEmail(string email)
        {
            return GetEntityByCondition<DatUser>("Email='" + email + "'") as DatUser;
        }

        /// <summary>
        /// 获到操作权限
        /// </summary>
        /// <param name="userid">用户</param>
        /// <param name="functionid">功能项</param>
        /// <returns>操作</returns>
        public String[] GetMenuOperation(string userid,string functionid)
        {
            var list = GetEntitysByCondition<UserMenu>(" UserID='" + userid + "' and FunctionID='" + functionid + "' and BarItems is not null");
            
            if (list == null || list.Count() ==0)
            {
                return "".Split(',');
            }
            else
            {
                return list.Select(p=>p.BarItems).ToArray();
            }

        }

        public static BUser  CreateInstance()
        {
            return new BUser();
        }
    }
}
